/**
 * @作者 Lucas
 * @创建时间 2020/5/15 15:44
 */
package com.lucas.springboot_restful_api.core;

import com.alibaba.fastjson.JSON;
import com.lucas.springboot_restful_api.exception.http.NotFoundException;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.LinkedHashMap;

@ControllerAdvice
public class GlobalResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
//        return false;
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter,
                                  MediaType mediaType, Class aClass,
                                  ServerHttpRequest request,
                                  ServerHttpResponse response) {

        String requestPath = request.getURI().getPath();
        String requestMethod = request.getMethodValue();
        int httpStatus = ((ServletServerHttpResponse) response).getServletResponse().getStatus();

        if (ObjectUtils.isEmpty(body)) {
            throw new NotFoundException(10001);
        }

        switch (HttpStatus.valueOf(httpStatus)) {
            case BAD_REQUEST:
                return body;
        }

        if (body instanceof UnifyResponse) {
            ((UnifyResponse) body).setRequest(requestMethod + " " + requestPath);
            return body;
        }

        if(body instanceof String) {
            return JSON.toJSONString(new UnifyResponse(
                    200,
                    "ok",
                    requestMethod + " " + requestPath,
                    body));
        }

        return new UnifyResponse(
                200,
                "ok",
                requestMethod + " " + requestPath,
                body);
    }


}
